<template>
  <div class="login">
    <a-form :form="form" @submit="handleSubmit" class="login-form">
      <a-form-item required label="用户名">
        <a-input
          allowClear
          size="large"
          v-decorator="[
          'username',
          { rules: [{ required: true, message: '请输入用户名...' }] },
        ]"
          placeholder="用户名..."
        >
          <a-icon slot="prefix" type="user" style="color: rgba(0,0,0,.25)" />
        </a-input>
      </a-form-item>
      <a-form-item required label="密码">
        <a-input-password
          size="large"
          v-decorator="[
          'password',
          { rules: [{ required: true, message: '请输入密码...' }] },
        ]"
          type="password"
          placeholder="密码"
        >
          <a-icon slot="prefix" type="lock" style="color: rgba(0,0,0,.25)" />
        </a-input-password>
      </a-form-item>
      <a-form-item>
        <div class="login-button">
          <a-button type="primary"
                    size="large"
                    shape="round"
                    ghost
                    :loading="loading"
                    html-type="submit">登录</a-button>
        </div>
      </a-form-item>
    </a-form>
  </div>
</template>

<script>
  import app from "../../../app"
  export default {
    name: "login",
    head: ()=>({ title: "登录界面 - "+app.name }),
    beforeCreate() {
      this.form = this.$form.createForm(this, { name: 'login' });
    },
    data: ()=>({
      loading: false,
    }),
    methods: {
      handleSubmit(e){
        e.preventDefault();
        this.form.validateFields((err, values) => {
          if (!err) {
            this.$axios.$post(`${app.api}/api/${app.apiVersion}/login/`, values)
              .then((resp)=>{
                if (resp.code === 200) {
                  this.$store.dispatch("SET_TOKEN", resp.data.token)
                  this.$store.dispatch("SET_USER", {
                    username: resp.data.username,
                    avatar: resp.data.avatar,
                  })
                  // 设置 token
                  this.$axios.setHeader('token', resp.data.token)

                  this.$message.success(resp.msg)

                  this.$router.push({ path: "/admin"})

                }else {
                  this.$message.warning(resp.msg)
                }
              }).catch((error)=>{
                // 错误处理
            })
          }
        });
      }
    }
  }
</script>

<style scoped>
  .login{
    margin: 0 auto;
    min-height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .login-form{
    min-width: 320px;
  }
  .login-button{
    margin-top: 10px;
    text-align: center;
  }
</style>
